package com.sto.stoapp.activity.aviation;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;

import com.sto.stoapp.StoApplication;
import com.sto.stoapp.activity.R;
import com.sto.stoapp.activity.StoBillFiterActivity;
import com.sto.stoapp.activity.StoLoginActivity;
import com.sto.stoapp.activity.administrator.system.AdminSystemSettingActivity;
import com.sto.stoapp.activity.sales.SalesProblemPieceSelectActivity;
import com.sto.stoapp.activity.sales.SalesTelphoneSmsActivity;
import com.sto.stoapp.activity.sales.SalesWdcpQueryActivity;
import com.sto.stoapp.activity.scanner.StoBusinessSetupActivity;
import com.sto.stoapp.activity.scanner.StoDeleteWrongScanningActivity;
import com.sto.stoapp.activity.scanner.StoRecordscheckActivity;
import com.sto.stoapp.activity.scanner.StoScanStayWarehourseActivity;
import com.sto.stoapp.activity.scanner.StoUploadMainActivity;
import com.sto.stoapp.adapter.SoleMainAdapter;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.entity.FunctionEntity;
import com.sto.stoapp.listener.OnBackClickListener;
import com.sto.stoapp.manager.AlarmClockManager;
import com.sto.stoapp.server.StoDownServer;
import com.sto.stoapp.service.TimingService;
import com.sto.stoapp.upload.UploadDataService;
import com.sto.stoapp.widget.BaseDialog;
import com.sto.stoapp.widget.StoHomeActivity;

import java.util.ArrayList;
import java.util.List;

import sto.android.app.StoPdaKeyEvent;

public class StoAviationScannerMainActivity extends StoHomeActivity {

    private GridView aviationScannerMainList;

    private SoleMainAdapter soleAdapter;

    // 按键映射
    private static final int[] MAPP_TO_KEY = {R.string.record_search,
            R.string.arrived_piece, R.string.send_piece,
            R.string.problem_piece, R.string.keep_ware_piece,
            R.string.bag_operation, R.string.vehicle_operation,
            R.string.h_received_piece, R.string.super_limits_search,
            R.string.del_error_code};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sto_aviation_scanner_main);
        this.setStoTitle(R.string.avi_scanner_title);
        this.register(HomeBroadAction.AVIATION_SCANNER_BROAD);
        initWidget();
//		UnSentDataManager.getInstance().setUnSent(
//				UploadDataManager.getInstance(this).getUnsendDataCount());
        initUnsentDataCount();
    }

    private void initWidget() {
        aviationScannerMainList = (GridView) findViewById(R.id.aviation_scanner_main_list);
        soleAdapter = new SoleMainAdapter(this, getResourceList());
        aviationScannerMainList.setAdapter(soleAdapter);
        aviationScannerMainList
                .setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                                            int arg2, long arg3) {
                        arg1.setSelected(true);
                        TextView title = (TextView) arg1
                                .findViewById(R.id.res_test);
                        clickItemEvent(title.getText().toString());
                    }
                });
    }

    private void clickItemEvent(String title) {
        // 航空-到件
        if (title.equals(getText(R.string.to_piece))) {
            checkTimeSyn(StoAviationToPieceActivity.class, this, "");
        }
        // 航空-发件
        else if (title.equals(getText(R.string.send_piece))) {
            checkTimeSyn(StoAviationSendPieceActivity.class, this, "");
        }
        // 航空-问题件
        else if (title.equals(getText(R.string.problem_piece))) {
            checkTimeSyn(SalesProblemPieceSelectActivity.class, this,
                    HomeBroadAction.AVIATION_SCANNER_BROAD);
        }
        // 航空-留仓件
        else if (title.equals(getText(R.string.stay_warehourse_piece))) {
            checkTimeSyn(StoScanStayWarehourseActivity.class, this,
                    HomeBroadAction.AVIATION_SCANNER_BROAD);
        }
        // 航空-包操作
        else if (title.equals(getText(R.string.bag_operation))) {
            checkTimeSyn(StoAviBagOperateActivity.class, this,
                    HomeBroadAction.AVIATION_SCANNER_BROAD);
        }
        // 航空-车辆操作
        else if (title.equals(getText(R.string.vehicle_operation))) {
            checkTimeSyn(StoAviationCarOperatActivity.class, this,
                    HomeBroadAction.AVIATION_SCANNER_BROAD);
        }
        // 航空-24小时扫描
        else if (title.equals(getText(R.string.h_received_piece))) {
            checkTimeSyn(StoAviTwentyFourHoursActivity.class, this, "");
        }
        // 航空-无点超派
        else if (title.equals(getText(R.string.super_limits_search))) {
            Intent intent = new Intent(this, SalesWdcpQueryActivity.class);
            intent.putExtra("busiType", HomeBroadAction.AVIATION_SCANNER_BROAD);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        // 航空-删除错扫
        else if (title.equals(getText(R.string.del_error_code))) {
            Intent intent = new Intent(this,
                    StoDeleteWrongScanningActivity.class);
            intent.putExtra("busiType", HomeBroadAction.AVIATION_SCANNER_BROAD);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        // 航空-记录查询
        else if (title.equals(getText(R.string.record_search))) {
            Intent intent = new Intent(this, StoRecordscheckActivity.class);
            intent.putExtra("busiType", HomeBroadAction.AVIATION_SCANNER_BROAD);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        // 航空-记录上传
        else if (title.equals(getText(R.string.record_upload))) {
            Intent intent = new Intent(this, StoUploadMainActivity.class);
            intent.putExtra("busiType", HomeBroadAction.AVIATION_SCANNER_BROAD);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        // 航空-业务设置
        else if (title.equals(getText(R.string.business_settings))) {
            Intent intent = new Intent(this, StoBusinessSetupActivity.class);
            intent.putExtra("busiType", HomeBroadAction.AVIATION_SCANNER_BROAD);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        // 航空-电话短信
        else if (title.equals(getText(R.string.telphone_sms))) {
            Intent intent = new Intent(this, SalesTelphoneSmsActivity.class);
            intent.putExtra("busiType", HomeBroadAction.AVIATION_SCANNER_BROAD);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        // 航空-系统设置
        else if (title.equals(getText(R.string.system_settings))) {
            Intent intent = new Intent(this, AdminSystemSettingActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra(HomeBroadAction.BROAD_TYPE,
                    HomeBroadAction.AVIATION_SCANNER_BROAD);
            startActivity(intent);
        }
        //航空-拦截件
        else if(title.equals(getText(R.string.filter))){
            Intent intent=new Intent(this, StoBillFiterActivity.class);
            intent.putExtra("busiType", HomeBroadAction.AVIATION_SCANNER_BROAD);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        // 航空-用户切换
        else {
            onBackPressed();
        }

    }

    private void checkTimeSyn(final Class<?> c, final Context context,
                              final String type) {
        if (!(StoFilePreference
                .getInstance(StoAviationScannerMainActivity.this)
                .getsetTimeSynch())) {
            final BaseDialog dialog = new BaseDialog(this);
            dialog.setTitles(getString(R.string.synch_time_hint));
            dialog.show();
            dialog.setOnBackClickListener(new OnBackClickListener() {

                @Override
                public void onBackClickListener(boolean res) {
                    dialog.dismiss();
                    if (res) {
                        Intent intent = new Intent(context, c);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.putExtra("busiType", type);
                        startActivity(intent);
                    }
                }
            });
        } else {
            Intent intent = new Intent(context, c);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("busiType", type);
            this.startActivity(intent);
        }
    }

    private List<FunctionEntity> getResourceList() {
        List<String> resList = new ArrayList<String>();
        int[] picIds;
        if (StoFilePreference.getInstance(this).get24Switch()) {
            picIds = new int[]{R.drawable.arrived_piece, R.drawable.send_piece,
                    R.drawable.problem_piece, R.drawable.keep_ware_piece,
                    R.drawable.bag_operation, R.drawable.vehicle_operation,
                    R.drawable.h_received_piece,
                    R.drawable.super_limits_search,
                    R.drawable.del_error_code, R.drawable.record_search,
                    R.drawable.record_upload, R.drawable.business_settings,
                    R.drawable.kai_after_sales, R.drawable.telphone_sms,
                    R.drawable.bill_filter, R.drawable.system_settings, R.drawable.logout};
        } else {
            picIds = new int[]{R.drawable.arrived_piece, R.drawable.send_piece,
                    R.drawable.problem_piece, R.drawable.keep_ware_piece,
                    R.drawable.bag_operation, R.drawable.vehicle_operation,
                    //	R.drawable.h_received_piece,
                    R.drawable.super_limits_search,
                    R.drawable.del_error_code, R.drawable.record_search,
                    R.drawable.record_upload, R.drawable.business_settings,
                    R.drawable.kai_after_sales, R.drawable.telphone_sms,
                    R.drawable.bill_filter, R.drawable.system_settings, R.drawable.logout};
        }

        resList.add(getText(R.string.arrived_piece).toString());
        resList.add(getText(R.string.send_piece).toString());
        resList.add(getText(R.string.problem_piece).toString());
        resList.add(getText(R.string.keep_ware_piece).toString());
        resList.add(getText(R.string.bag_operation).toString());
        resList.add(getText(R.string.vehicle_operation).toString());
        if (StoFilePreference.getInstance(this).get24Switch()) {
            resList.add(getText(R.string.h_received_piece).toString());
        }
        resList.add(getText(R.string.super_limits_search).toString());
        resList.add(getText(R.string.del_error_code).toString());
        resList.add(getText(R.string.record_search).toString());
        resList.add(getText(R.string.record_upload).toString());
        resList.add(getText(R.string.business_settings).toString());
        resList.add(getText(R.string.telphone_sms).toString());
        resList.add(getText(R.string.system_settings).toString());
        resList.add(getText(R.string.filter).toString());
        resList.add(getText(R.string.logout).toString());

        List<FunctionEntity> functionList = new ArrayList<FunctionEntity>();
        for (int i = 0; i < resList.size(); i++) {
            FunctionEntity entity = new FunctionEntity();
            entity.setTitle(resList.get(i));
            entity.setPicId(picIds[i]);
            functionList.add(entity);
        }
        return functionList;
    }

    /**
     * 退回到登入界面
     */
    @Override
    public void onBackPressed() {
        // new AlertDialog.Builder(this)
        // .setTitle(R.string.prompt)
        // .setMessage(R.string.change_user)
        // .setPositiveButton(R.string.change,
        // new DialogInterface.OnClickListener() {
        //
        // @Override
        // public void onClick(DialogInterface dialog,
        // int which) {
        // // 恢复时间同步和订单状态
        // Intent intent = new Intent(
        // StoAviationScannerMainActivity.this,
        // StoLoginActivity.class);
        // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        // startActivity(intent);
        // stopStoService();
        // finish();
        // }
        // })
        // .setNegativeButton(R.string.cancel,
        // new DialogInterface.OnClickListener() {
        //
        // @Override
        // public void onClick(DialogInterface dialog,
        // int which) {
        // dialog.dismiss();
        // }
        // }).setCancelable(false).show();
        final BaseDialog dialog = new BaseDialog(this);
        dialog.setTitles(this.getText(R.string.change_user).toString());
        dialog.show();
        dialog.getvMessage().setVisibility(View.GONE);
        dialog.getvPresentation().setVisibility(View.GONE);
        dialog.setOnBackClickListener(new OnBackClickListener() {

            @Override
            public void onBackClickListener(boolean res) {
                dialog.dismiss();
                if (res) {
                    // 恢复时间同步和订单状态
                    Intent intent = new Intent(
                            StoAviationScannerMainActivity.this,
                            StoLoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                    stopStoService();
                    //	new LogoutThread(StoAviationScannerMainActivity.this, null, false).start();
                    finish();
                }
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
//		// 退出
        if (intent.getStringExtra(AlarmClockManager.ALARM_CLOCK_TYPE) != null) {
            if ((Intent.FLAG_ACTIVITY_CLEAR_TOP & intent.getFlags()) != 0
                    && intent
                    .getStringExtra(AlarmClockManager.ALARM_CLOCK_TYPE)
                    .equals(HomeBroadAction.ALARM_LOGOUT)) {
                Intent logoutIntent = new Intent(this, StoLoginActivity.class);
                startActivity(logoutIntent);
                stopStoService();
                finish();
            }
        }
    }

//	/**
//	 * 按键映射 数字键映功能，0代表列表第10项
//	 */
//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		if (keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9) {
//			clickItemEvent(getString(MAPP_TO_KEY[keyCode - KeyEvent.KEYCODE_0]));
//		}
//		return super.onKeyDown(keyCode, event);
//	}

    /**
     * 小退 返回航空选择界面
     */
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        keyCode= StoApplication.getStoJni().getEventFuction(keyCode);
        if (keyCode == StoPdaKeyEvent.KEYCODE_DEL) {
            startActivity(new Intent(this, StoAviationSelectActivity.class)
                    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
            this.finish();
        }
        return super.onKeyUp(keyCode, event);
    }


    /**
     * 切换用户时 停止后台服务
     */
    private void stopStoService() {
        // 退出的时候关闭后台服务
        StoFilePreference.getInstance(this).clearTimeSynData();
        stopService(new Intent(this, StoDownServer.class));
        stopService(new Intent(this, UploadDataService.class));
        stopService(new Intent(this, TimingService.class));
    }

}
